Combination Sum II

Given a collection of candidate numbers (C) and a target number (T),
find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.
  • For example, given candidate set 10,1,2,7,6,1,5 and target 8,
  • A solution set is: [1, 7],[1, 2, 5] ,[2, 6] ,[1, 1, 6]

题目大意:给定一个数组和一个目标值,找出数组中所有和等于目标值的数的组合。要求数组中的数在一个组合中只出现一次,组合中的数以递增形式存储。但是如果数组中某个数出现了多次,组合中的该数也可出现多次,但是次数不超过数组中出现的次数。

题目难度:Medium

import java.util.*;

/**
 * Created by gzdaijie on 16/5/21
 * DFS
 * 与39不同的是,每个数只能用一次,为了避免重复,前缀不允许相同即可
 * 前缀不允许相同,即假设数组为1,2,3,4,4,4,前缀为1,2,3,递归时不允许出现多个1,2,3,4
 */
public class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        Arrays.sort(candidates);

        ArrayList tmp = new ArrayList();
        combination(candidates, target, result,tmp, 0);
        return result;
    }

    private void combination(int[] candidates, int target, List<List<Integer>> result, ArrayList<Integer> tmp, int k) {
        if (target == 0) {
            result.add((ArrayList<Integer>) tmp.clone());
            return;
        }
        int len = candidates.length;
        for (int i = k; i < len && candidates[i] <= target; i++) {
            if (i != k && candidates[i] == candidates[i - 1]) continue;
            tmp.add(candidates[i]);
            combination(candidates, target - candidates[i],result, tmp, i + 1);
            tmp.remove(tmp.size() - 1);
        }
    }
}
gzdaijie            updated 2016-05-21 01:36:16

results matching ""

    No results matching ""